package niu.toy.spring.mvc.impl;


import cn.hutool.core.lang.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.regex.Pattern;

public class RedirectView extends AbstractView  {

    public RedirectView(String url) {
        this.setUrl(url);
    }

    /**
     *发送重定向连接到Http客户端
     */
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
                                           HttpServletResponse response) throws IOException {
        String targetUrl = createTargetUrl(model, request);
        // Redirect
        sendRedirect(request, response, targetUrl,true);
    }

    /**
     * 模型值不转换为参数
     */
    protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request)
            throws UnsupportedEncodingException {
        StringBuilder targetUrl = new StringBuilder();
        String url = getUrl();
        Assert.state(url != null, "'url' not set");

        if (getUrl().startsWith("/")) {
            // Do not apply context path to relative URLs.
            targetUrl.append(getContextPath(request));
        }
        targetUrl.append(getUrl());

        return targetUrl.toString();
    }

    private String getContextPath(HttpServletRequest request) {
        String contextPath = request.getContextPath();
        while (contextPath.startsWith("//")) {
            contextPath = contextPath.substring(1);
        }
        return contextPath;
    }

    /**
     * 发送重定向连接到Http客户端
     */
    protected void sendRedirect(HttpServletRequest request, HttpServletResponse response,
                                String targetUrl, boolean http10Compatible) throws IOException {
        boolean isRemoteHost=true;
        String encodedURL = (isRemoteHost ? targetUrl : response.encodeRedirectURL(targetUrl));
        if (http10Compatible) {
            response.sendRedirect(encodedURL);
        } else {
            response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            response.setHeader("Location", encodedURL);
        }
    }


}
